package com.cxs.utils;

import cn.hutool.core.util.IdUtil;
import com.cxs.dto.UserDTO;
import com.cxs.model.User;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Project: postman-demo
 * @Author: cxs2014501@163.com
 * @Create: 2022/11/8 13:43
 * @Description:
 **/
public class DataUtil {

    private static List<User> userList = new ArrayList<>();

    static {
        for (int i = 0; i < 5; i++) {
            userList.add(
                    User.builder()
                            .id(IdUtil.randomUUID())
                            .username("测试用户" + i)
                            .password(IdUtil.simpleUUID())
                            .localDateTime(LocalDateTime.now().minusHours(i))
                            .build()
            );
        }
    }

    public static List<User> getUserList(){
        return userList;
    }

    public static Integer removeUserById(String id){
        Integer count = userList.size();
        Iterator<User> iterator = userList.iterator();
        while (iterator.hasNext()){
            User next = iterator.next();
            if (next.getId().equals(id)) {
                iterator.remove();
            }
        }
        return count - userList.size();
    }

    public static Integer saveUser(UserDTO user) {
        Integer count = userList.size();
        User u = new User();
        BeanUtils.copyProperties(user, u);
        u.setLocalDateTime(LocalDateTime.now());
        User idUser = findUserById(user.getId());
        if (ObjectUtils.isEmpty(idUser)) {
            userList.add(u);
        }
        return userList.size() - count;
    }

    public static User findUserById(String id) {
        User u = null;
        Iterator<User> iterator = userList.iterator();
        while (iterator.hasNext()){
            User next = iterator.next();
            if (next.getId().equals(id)) {
                u = next;
            }
        }
        return u;
    }
}
